<?php
/**
 * Foreign Key Validation
 * Ensures that a foreign key is defined for a column.
 *
 * @package     Visi
 * @subpackage  Rules
 * @author      Luke Visinoni <luke.visinoni@gmail.com>
 * @copyright   (c) 2010 Luke Visinoni <luke.visinoni@gmail.com>
 * @version     $Id$
 */
class Visi_Rule_ForeignKey extends Q_Rule_Abstract {

    protected $_params = array(
        'foreignModel' => null,
        'foreignColumn' => null,
    );
    
    /**
     * Ensure that the specified value is in the foreign table
     */
    public function isValid($value) {
    
        $model = $this->getParam('foreignModel');
        $column = $this->getParam('foreignColumn');
        if (empty($model) || empty($column)) {
            throw new Q_Rule_Exception('You must provide both a "foreignModel" and "foreignColumn".');
        }
        if (!is_null($value)) {
            $select = $model->select()->where("{$column} = ?", $value);
            if ($row = $model->fetchRow($select)) {
                return true;
            }
        }
        return false;
    
    }

}